package xyz.labmem.main.config.redis;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import xyz.labmem.main.constants.ConstantsCache;

import java.time.Duration;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Redis缓存配置
 */
@Configuration
public class RedisCacheConfig {

    /**
     * 自定义Redis缓存管理器
     *
     * @param connectionFactory 缓存连接
     * @return Redis缓存管理器
     */
    @Bean
    @Primary
    public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {
        /*默认缓存配置，从不过期*/
        RedisCacheConfiguration defaultConfiguration = RedisCacheConfiguration
                .defaultCacheConfig()
                .disableCachingNullValues();
        return RedisCacheManager
                .builder(RedisCacheWriter.lockingRedisCacheWriter(connectionFactory))
                .cacheDefaults(defaultConfiguration)
                .withInitialCacheConfigurations(getOtherConfiguration(defaultConfiguration))
                .transactionAware()
                .build();
    }

    /**
     * 获取自定义缓存Map
     *
     * @param defaultConfiguration 默认缓存配置
     * @return 自定义缓存Map
     */
    private Map<String, RedisCacheConfiguration> getOtherConfiguration(RedisCacheConfiguration defaultConfiguration) {
        Map<String, RedisCacheConfiguration> otherConfiguration = new LinkedHashMap<>(1);
        /*自定义缓存过期策略。增加或减少策略，记得修改otherConfiguration初始大小*/
        otherConfiguration.put(ConstantsCache.REDIS_DEFAULT_CACHE_NAME, defaultConfiguration.entryTtl(Duration.ofSeconds(60)));
        return otherConfiguration;
    }

}
